using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml;
using System.Net;
using System.IO;

namespace Alia2.Pedometer
{
	/// <summary>
	/// Summary description for PedoForm
	/// </summary>
	public class PedoForm : System.Windows.Forms.Form
	{
		[DllImport("User32.dll")]
		protected static extern int SetClipboardViewer(int hWndNewViewer);

		[DllImport("User32.dll", CharSet=CharSet.Auto)]
		public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);

		[DllImport("user32.dll", CharSet=CharSet.Auto)]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		private System.Windows.Forms.RichTextBox outputMessages;

		IntPtr nextClipboardViewer;

		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public PedoForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			nextClipboardViewer = (IntPtr)SetClipboardViewer((int) this.Handle);

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			ChangeClipboardChain(this.Handle, nextClipboardViewer);
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.outputMessages = new System.Windows.Forms.RichTextBox();
			this.SuspendLayout();
			// 
            // outputMessages
			// 
			this.outputMessages.BorderStyle = System.Windows.Forms.BorderStyle.None;
			this.outputMessages.Dock = System.Windows.Forms.DockStyle.Fill;
			this.outputMessages.Location = new System.Drawing.Point(0, 0);
            this.outputMessages.Name = "outputMessage";
			this.outputMessages.ReadOnly = true;
			this.outputMessages.Size = new System.Drawing.Size(292, 273);
			this.outputMessages.TabIndex = 0;
            this.outputMessages.Text = "outputMessage";
			this.outputMessages.WordWrap = false;
			// 
            // PedoForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(292, 273);
			this.Controls.Add(this.outputMessages);
			this.Name = "PedoForm";
			this.Text = "Alia2 Pedometer";
			this.ResumeLayout(false);

		}
		#endregion

		protected override void WndProc(ref System.Windows.Forms.Message m)
		{
			// defined in winuser.h
			const int WM_DRAWCLIPBOARD = 0x308;
			const int WM_CHANGECBCHAIN = 0x030D;

			switch(m.Msg)
			{
				case WM_DRAWCLIPBOARD:
					CheckClipboardData();
					SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
					break;

				case WM_CHANGECBCHAIN:
					if (m.WParam == nextClipboardViewer)
						nextClipboardViewer = m.LParam;
					else
						SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
					break;

				default:
					base.WndProc(ref m);
					break;
			}	
		}

		void CheckClipboardData()		
		{
			try
			{
				IDataObject iData = new DataObject();  
				iData = Clipboard.GetDataObject();
                string strClipboardText;
                string strOutputText = "";

                if (iData.GetDataPresent(DataFormats.Text))
                {
                    strClipboardText = (string)iData.GetData(DataFormats.Text);

                    // Check if there are URNs in the clipboard
                    // e.g.: ED2K URNs -->  ed2k://|file|{filename}|{filesize}|{filehash}|/
                    Regex URNtoFind = new Regex(Properties.Settings.Default.regexURN, RegexOptions.IgnoreCase);
                    URNtoFind.Match(strClipboardText);

                    foreach (Match rm in URNtoFind.Matches(strClipboardText))
                    {
                        // Check HASH pedometer
                        // TODO: pedometer URL template in preferences page
                        string strURLTemplate = Properties.Settings.Default.serviceURL;

                        WebRequest wrGETURL = HttpWebRequest.Create(strURLTemplate + rm.Groups["filehash"].Value);

                        // TODO: proxy settings in user preferences
                        if (Properties.Settings.Default.proxyBypass)
                        {
                            // Use proxy settings from the preferences page
                            WebProxy myProxy = new WebProxy(Properties.Settings.Default.proxyServer, Properties.Settings.Default.proxyPort);
                            myProxy.BypassProxyOnLocal = true;

                            wrGETURL.Proxy = myProxy;
                        }

                        // Retrieve XML document  
                        XmlReader reader = XmlReader.Create(wrGETURL.GetResponse().GetResponseStream());
                        
                        StringWriter txtWriter = new StringWriter();
                        // TODO: get from resources
                        txtWriter.WriteLine(Properties.Resources.outputMessage,
                            rm.Index,
                            rm.Groups["filename"].Value,
                            rm.Groups["filesize"].Value,
                            rm.Groups["filehash"].Value,
                            reader.ReadElementString()
                        );
                        strOutputText += txtWriter.ToString();
                    }
                }
                else
                    // TODO: get from resources
                    strOutputText = "[El portapapeles no contiene texto]";

                outputMessages.Text = strOutputText;
			}
			catch(Exception e)
			{
				MessageBox.Show(e.ToString());
			}
		}
	}
}
